﻿CREATE PROCEDURE [maint].[RestoreDiffFromDevice]
@DbName [sysname], @DeviceName [sysname], @FilePosition INT, @Recover BIT=0, @OutputDiagnostics BIT=0
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @RC int, @ErrorMessage nvarchar(max);
	SET @RC = 0;

	IF(@OutputDiagnostics = 1)
		BEGIN
			PRINT OBJECT_NAME(@@PROCID)
			PRINT N'	@DbName = N''' + ISNULL(@DbName,N'NULL') + ''''
			PRINT N'	@DeviceName = N''' + ISNULL(@DeviceName,N'NULL') + ''''
			PRINT N'	@FilePosition = N''' + ISNULL(CAST(@FilePosition AS nvarchar),N'NULL') + ''''
			PRINT N'	@Recover = N''' + ISNULL(CAST(@Recover AS nvarchar),N'NULL') + ''''
		END
		
	BEGIN TRY

		DECLARE @DiffRestoreStatement nvarchar(1024);
		SET @DiffRestoreStatement = 
			N'RESTORE DATABASE [' + @DbName + ']
			FROM [' + @DeviceName + ']
			WITH 
			FILE = ' + CAST(@FilePosition AS nvarchar)
			+ (CASE
				WHEN @Recover = 1 THEN ', RECOVERY'
				ELSE ', NORECOVERY'
			END)
			+ ', STATS = 10';

		IF(@OutputDiagnostics = 1)
			PRINT '	@DiffRestoreStatement = ' + CHAR(10) + ISNULL(@DiffRestoreStatement,N'NULL') + CHAR(10);
			
		DECLARE @StartDate datetime
		SET @StartDate = GETDATE();

		EXEC(@DiffRestoreStatement);
		
	END TRY
	BEGIN CATCH
		SET @RC = ERROR_NUMBER();
		EXEC [util].[GetErrorOutput] @Output = @ErrorMessage OUTPUT;
	END CATCH

	DECLARE @FinishDate datetime;
	SET @FinishDate = GETDATE();
	
	EXEC @RC = [maint].[LogRestore]
		 @DbName = @DbName
		,@DeviceName = @DeviceName
		,@FilePosition = @FilePosition
		,@Type = 5
		,@StartDate = @StartDate
		,@FinishDate = @FinishDate
		,@RecoverStatus = @Recover
		,@ErrorCode = @RC
		,@Output = @ErrorMessage
		,@OutputDiagnostics = @OutputDiagnostics;

	RETURN(@RC);
END;